﻿using ReactiveUI;
using RFID_EnergyTeam.ViewModel;
using StudyKitLib;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RFID_EnergyTeam
{
    public partial class Form1 : Form, IViewFor<MainViewModel>
    {
        ServiceReference1.Container context = new ServiceReference1.Container(new Uri("http://localhost:19259/odata"));

        public static string CarNo = String.Empty;
        public static string UID = String.Empty;
        public static long PortNO;
        public int i;
        public static RF1356.REPLY reply; // 리턴 상태를 반환하는 변수

        public MainViewModel ViewModel { get; set; }
        object IViewFor.ViewModel
        {
            get
            {
                return ViewModel;
            }

            set
            {
                ViewModel = (MainViewModel)value;
            }
        }
        MainViewModel IViewFor<MainViewModel>.ViewModel
        {
            get
            {
                return ViewModel;
            }

            set
            {
                ViewModel = value;
            }
        }

        public Form1()
        {          
            InitializeComponent();

            ViewModel = new MainViewModel();           

            this.Bind(ViewModel, x => x.CarNo, x => x.textBox2.Text);
            this.Bind(ViewModel, x => x.LblTime, x => x.lblTime.Text);
            this.Bind(ViewModel, x => x.OutText, x => x.textBox4.Text);
            this.BindCommand(ViewModel, x => x.AddingText, x => x.button2);
            this.textBox4.TextChanged += (s,e) => (this.lstBox1.Items.Add(this.textBox4.Text));
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 frm = new Form2();
            frm.ShowDialog();
        }
        private void Form1_Load(object sender, EventArgs e)
        {           
            this.carsTableAdapter.Fill(this.parkingDataSet.Cars);
           
            timer2.Enabled = true;

            this.btnRegister.Enabled =false;

            for (i = 1; i < 11; i++)    // COM1~10            
                cmbPort1.Items.Add("COM" + i.ToString());
            cmbPort1.SelectedIndex = 0;

            cmbModule.Items.Add("STS-1000");
            cmbModule.Items.Add("STS-1000(Multi)");
            cmbModule.SelectedIndex = 0;

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
        }
        private void timer2_Tick(object sender, EventArgs e)
        {
            this.lblTime.Text = DateTime.Now.ToString("HH:mm:ss");
        }
        private void timer3_Tick(object sender, EventArgs e)
        {

        }

        private void carsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {

            this.Validate();
            this.carsBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.parkingDataSet);

        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {
            if (textBox1.Text != "" & textBox2.Text != "" & textBox3.Text != "")
            {
                this.btnRegister.Enabled = true;
            }
            else if (textBox1.Text == "" & textBox2.Text != "" & textBox3.Text != "")
            {
                this.btnRegister.Enabled = false;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                int tagCnt = 0;
                int i = 0;
                int flag = 0;
                string SerialNumbers = String.Empty;

                if (cmbModule.SelectedIndex == 0)
                {
                    reply = RF1356.RFReadSerialNO(PortNO, ref SerialNumbers);

                    switch (reply)
                    {
                        case RF1356.REPLY.RF_OK:

                            //tagCnt = int.Parse(SerialNumbers.Substring(0, 2));                       

                            UID = String.Empty;

                            string str = SerialNumbers.Substring(2, 16);
                            CarNo = String.Empty;

                            for (i = 0; i < 8; i++)
                                UID = str.Substring(2 * i, 2) + UID;

                            // 인식된 태그가 주차된 태그와 일치하는 여부 확인

                            this.textBox1.Text = UID;

                            break;

                        case RF1356.REPLY.NO_TRANSPONDER:
                            break;

                        case RF1356.REPLY.RF_ERR:
                            break;

                        default:
                            break;
                    }
                }
                else
                {
                    byte[] bUID = new byte[9];
                    byte len = new byte();
                    string strUID = String.Empty;
                    string str = String.Empty;

                    int state = CarKitMultiAPI.ISO15693_Inventory(0, ref bUID[0], ref len);

                    if (state == CarKitMultiAPI.LIB_SUCCESS)
                    {
                        while (true)
                        {
                            str = string.Format("{0:X2} ", bUID[--len]);
                            strUID = strUID + str;

                            if (len == 1)
                                break;
                        }

                        UID = strUID.Replace(" ", "");
                        CarNo = String.Empty;

                        // 인식된 태그가 주차된 태그와 일치하는 여부 확인

                        this.textBox1.Text = UID;

                        //if (flag != 1)
                        //{

                        //    MessageBox.Show("등록되지 않은 차량태그입니다.\n다시 태그를 인식해 주십시오.", "Error");

                        //    return;
                        //}


                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            try
            {
                int port = cmbPort1.SelectedIndex + 1;

                if (cmbModule.SelectedIndex == 0)
                {
                    if (!RF1356.RFReaderOpen(port))
                    {
                        MessageBox.Show("COM 포트를 열 수가 없습니다.", "Error",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Exclamation,
                                    MessageBoxDefaultButton.Button1);
                    }
                    else
                    {
                        cmbModule.Enabled = false;
                        cmbPort1.Enabled = false;
                        btnOpen.Enabled = false;
                        btnClose.Enabled = true;

                        PortNO = port;
                    }
                }
                else
                {
                    // Port Open(baudrate : 19200)
                    int state = CarKitMultiAPI.rf_init_com(cmbPort1.SelectedIndex + 1, 19200);
                    //state = modeChange("15693");

                    if (state != CarKitMultiAPI.LIB_SUCCESS)
                    {
                        MessageBox.Show("COM 포트를 열 수가 없습니다.", "Error",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Exclamation,
                                    MessageBoxDefaultButton.Button1);
                    }
                    else
                    {

                        cmbModule.Enabled = false;
                        cmbPort1.Enabled = false;
                        btnOpen.Enabled = false;
                        btnClose.Enabled = true;

                        PortNO = port;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void btnClose_Click_1(object sender, EventArgs e)
        {
            try
            {
                if (cmbModule.SelectedIndex == 0)
                {
                    if (RF1356.RFReaderClose(PortNO))
                    {
                        cmbModule.Enabled = true;
                        cmbPort1.Enabled = true;
                        btnOpen.Enabled = true;
                        btnClose.Enabled = false;


                        try
                        {
                            if (RF1356.RFReaderIsOpen(PortNO))
                                RF1356.RFReaderClose(PortNO);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                    }
                }
                else
                {
                    int state = CarKitMultiAPI.rf_ClosePort();


                    if (state == CarKitMultiAPI.LIB_SUCCESS)
                    {
                        cmbModule.Enabled = true;
                        cmbPort1.Enabled = true;
                        btnOpen.Enabled = true;
                        btnClose.Enabled = false;

                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
